import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'package:crypto/crypto.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../data/models/album.dart';

/// 相册缓存服务
class AlbumCacheService {
  static const String _cacheKey = 'album_cache_data';
  static const String _cacheDirName = 'album_thumbnails';
  static const String _lastUpdateTimeKey = 'album_cache_last_update';

  /// 缓存有效期（毫秒）- 设置为24小时
  static const int _cacheValidDuration = 24 * 60 * 60 * 1000;

  late final Directory _cacheDir;
  bool _isInitialized = false;

  /// 初始化缓存目录
  Future<void> init() async {
    if (_isInitialized) return;

    try {
      final appDir = await getApplicationDocumentsDirectory();
      _cacheDir = Directory(path.join(appDir.path, _cacheDirName));

      if (!(await _cacheDir.exists())) {
        await _cacheDir.create(recursive: true);
      }

      _isInitialized = true;
    } catch (e) {
      debugPrint('初始化相册缓存目录失败: $e');
      rethrow;
    }
  }

  /// 获取相册缓存
  Future<List<Album>?> getAlbumCache() async {
    await init();

    try {
      final prefs = await SharedPreferences.getInstance();
      final cacheData = prefs.getString(_cacheKey);
      final lastUpdateTime = prefs.getInt(_lastUpdateTimeKey) ?? 0;

      // 检查缓存是否过期
      final now = DateTime.now().millisecondsSinceEpoch;
      if (cacheData == null || now - lastUpdateTime > _cacheValidDuration) {
        return null;
      }

      // 解析缓存的基本信息
      final List<dynamic> cachedList = jsonDecode(cacheData);
      final List<Album> albums = [];

      for (final item in cachedList) {
        try {
          final album = Album.fromJson(item);

          // 加载缩略图
          final thumbnailFile = File(
            path.join(_cacheDir.path, '${album.id}.thumbnail'),
          );
          if (await thumbnailFile.exists()) {
            album.thumbnailData = await thumbnailFile.readAsBytes();
          }

          albums.add(album);
        } catch (e) {
          debugPrint('解析相册缓存项失败: $e');
        }
      }

      return albums;
    } catch (e) {
      debugPrint('获取相册缓存失败: $e');
      return null;
    }
  }

  /// 保存相册缓存
  Future<void> saveAlbumCache(List<Album> albums) async {
    await init();

    try {
      // 保存基本信息
      final List<Map<String, dynamic>> albumJsonList = [];
      for (final album in albums) {
        albumJsonList.add(album.toJson());

        // 保存缩略图
        if (album.thumbnailData != null) {
          final thumbnailFile = File(
            path.join(_cacheDir.path, '${album.id}.thumbnail'),
          );
          await thumbnailFile.writeAsBytes(album.thumbnailData!);
        }
      }

      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(_cacheKey, jsonEncode(albumJsonList));
      await prefs.setInt(
        _lastUpdateTimeKey,
        DateTime.now().millisecondsSinceEpoch,
      );
    } catch (e) {
      debugPrint('保存相册缓存失败: $e');
    }
  }

  /// 清除相册缓存
  Future<void> clearAlbumCache() async {
    await init();

    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_cacheKey);
      await prefs.remove(_lastUpdateTimeKey);

      // 清除缩略图文件
      final files = await _cacheDir.list().toList();
      for (final file in files) {
        if (file is File) {
          await file.delete();
        }
      }
    } catch (e) {
      debugPrint('清除相册缓存失败: $e');
    }
  }

  /// 缓存是否过期
  Future<bool> isCacheExpired() async {
    final prefs = await SharedPreferences.getInstance();
    final lastUpdateTime = prefs.getInt(_lastUpdateTimeKey) ?? 0;
    final now = DateTime.now().millisecondsSinceEpoch;

    return now - lastUpdateTime > _cacheValidDuration ||
        !prefs.containsKey(_cacheKey);
  }

  /// 生成相册ID（基于路径的哈希值）
  String generateAlbumId(String path) {
    final bytes = utf8.encode(path);
    final digest = md5.convert(bytes);
    return digest.toString();
  }
}
